<template>
    <div class="reservation-management">
        <!-- 搜索框 -->
        <div class="search-container">
            <el-input v-model="search" placeholder="请输入目录名称或年度查询" clearable @clear="handleClearSearch"
                class="search-input" />
            <el-button type="primary" @click="handleAddReservation">新增</el-button>
            <el-button type="success" @click="handleExport">导出为 Excel</el-button>
        </div>

        <!-- 表格 -->
        <el-table :data="reservations" stripe border>
            <el-table-column prop="journal_name" label="期刊名称" />
            <el-table-column prop="year" label="年度" />
            <el-table-column prop="volume" label="卷号" />
            <el-table-column prop="issue" label="期号" />
            <el-table-column prop="borrow_count" label="借阅次数" />
            <el-table-column prop="feedback_count" label="用户反馈次数" />
            <el-table-column label="操作">
                <template #default="{ row }">
                    <el-switch v-model="row.isdel" :active-value="1" :inactive-value="-1"
                        @change="handleStatusChange(row)" active-text="预定" inactive-text="不预定" />
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination background layout="prev, pager, next" :total="total" :page-size="pageSize"
            v-model:current-page="currentPage" @current-change="handlePageChange" class="pagination" />

        <!-- 新增表单弹框 -->
        <el-dialog title="新增年度征订记录" v-model="dialogVisible" @close="resetForm" width="50%">
            <el-form :model="form" ref="formRef" label-width="120px">
                <el-form-item label="期刊名称" prop="journal_id">
                    <el-select v-model="form.journal_id" placeholder="请选择期刊名称">
                        <el-option v-for="directory in filteredJournals" :key="directory.journal_id"
                            :label="directory.journal_name" :value="directory.journal_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="年份" :rules="[{ required: true, message: '请输入年份', trigger: 'blur' }]">
                    <el-input v-model="form.year" placeholder="请输入年份" />
                </el-form-item>
                <el-form-item label="卷号" :rules="[{ required: true, message: '请输入卷号', trigger: 'blur' }]">
                    <el-input v-model="form.volume" placeholder="请输入卷号" />
                </el-form-item>
                <el-form-item label="期号" :rules="[{ required: true, message: '请输入期号', trigger: 'blur' }]">
                    <el-input v-model="form.issue" placeholder="请输入期号" />
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleAddSubmit">确定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, watch, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { nextYearReservationApi, journalDirectoryApi } from '@/request/apiService';
import * as XLSX from 'xlsx';

const reservations = ref([]); // 表格数据
const search = ref(''); // 搜索内容
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示数量
const total = ref(0); // 总记录数
const journals = ref([]); // 目录列表
const dialogVisible = ref(false); // 新增表单的显示状态
const form = ref({
    journal_id: null, // 目录ID
    year: '',
    volume: '',
    issue: ''
}); // 新增表单数据

// 获取目录列表
const fetchJournals = async () => {
    try {
        const res = await journalDirectoryApi.getDirectoryList({ page: 1, pageSize: 99999 });
        journals.value = res.data.map(directory => ({
            journal_id: directory.directory_id,
            journal_name: directory.journal_name,
        }));
    } catch (error) {
        console.error('获取目录列表失败', error);
    }
};


// 计算属性：去重后的期刊数据
const filteredJournals = computed(() => {
    const uniqueNames = new Set();
    return journals.value.filter((directory) => {
        if (!uniqueNames.has(directory.journal_name)) {
            uniqueNames.add(directory.journal_name);
            return true;
        }
        return false;
    });
});

// 获取年度征订记录
const fetchReservations = async () => {
    try {
        const { data, total: totalCount } = await nextYearReservationApi.getReservationList({
            page: currentPage.value,
            pageSize: pageSize.value,
            search: search.value // 搜索内容
        });
        reservations.value = data; // 设置表格数据
        total.value = totalCount; // 设置总记录数
    } catch (error) {
        console.error('获取年度征订记录失败', error);
    }
};

// 更新预定状态
const handleStatusChange = async (reservation) => {
    try {
        await nextYearReservationApi.deleteReservation({
            reservation_id: reservation.reservation_id,
            isdel: reservation.isdel
        });
    } catch (error) {
        console.error('更新预定状态失败', error);
        reservation.isdel = reservation.isdel === 1 ? -1 : 1; // 恢复之前的状态
    }
};

// 清空搜索框
const handleClearSearch = () => {
    search.value = '';
    currentPage.value = 1;
    fetchReservations();
};

// 分页改变时触发
const handlePageChange = (page) => {
    currentPage.value = page;
    fetchReservations();
};

// 新增按钮点击
const handleAddReservation = () => {
    form.value = {
        journal_id: null, // 清空目录 ID
        year: '',
        volume: '',
        issue: ''
    }; // 重置表单
    dialogVisible.value = true; // 显示新增弹框
};

// 提交新增数据
const handleAddSubmit = async () => {
    try {
        await nextYearReservationApi.addReservation(form.value);
        ElMessage.success('新增年度征订记录成功');
        dialogVisible.value = false;
        fetchReservations(); // 重新获取数据
    } catch (error) {
        console.error('新增失败', error);
        ElMessage.error('新增失败，请稍后再试');
    }
};

// 导出为 Excel
const handleExport = async () => {
    try {
        // 调用接口获取所有数据
        const { data } = await nextYearReservationApi.getReservationList({
            page: 1,
            pageSize: 99999, // 查询所有记录
            search: search.value // 搜索内容
        });

        if (data.length === 0) {
            ElMessage.warning('没有数据可导出');
            return;
        }

        // 转换数据为 Excel 格式
        const exportData = data.map((row) => ({
            期刊名称: row.journal_name,
            年度: row.year,
            卷号: row.volume,
            期号: row.issue,
            借阅次数: row.borrow_count,
            用户反馈次数: row.feedback_count,
            是否预定: row.isdel === -1 ? '预定' : '不预定'
        }));

        const worksheet = XLSX.utils.json_to_sheet(exportData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, '年度征订记录');
        XLSX.writeFile(workbook, '年度征订记录.xlsx');
    } catch (error) {
        console.error('导出失败:', error);
        ElMessage.error('导出失败，请稍后再试');
    }
};

// 页面加载时，获取年度征订数据和目录列表
onMounted(() => {
    fetchReservations();
    fetchJournals();
});

// 监听搜索变化自动获取数据
watch(search, () => {
    currentPage.value = 1; // 重置页码
    fetchReservations();
});
</script>

<style scoped>
.reservation-management {
    padding: 20px;
}

.search-container {
    display: flex;
    margin-bottom: 20px;
}

.search-input {
    width: 300px;
    margin-right: 20px;
}

.pagination {
    margin-top: 20px;
}

.dialog-footer {
    text-align: right;
}
</style>
